import json
from django.http import JsonResponse
from django.views import View
from rest_framework_jwt.settings import api_settings
from users.models import SysUser, SysUserSerializer


# Create your views here.
class LoginView(View):
    def post(self, request):
        try:
            # 关键步骤--解析前端的 JSON 数据
            data = json.loads(request.body.decode('utf-8'))
            username = data.get('username')
            password = data.get('password')

            # 查询用户
            user = SysUser.objects.get(username=username)
            if user.password == password:
                jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)

                return JsonResponse({'code': 200, 'msg': '登录成功',
                                     'user': SysUserSerializer(user).data,
                                     'token': token})
            else:
                return JsonResponse({'code': 500, 'msg': '账号或密码错误'})
        except SysUser.DoesNotExist:
            return JsonResponse({'code': 500, 'msg': '账户不存在'})
        except json.JSONDecodeError:
            return JsonResponse({'code': 500, 'msg': '请求数据格式错误，需为 JSON 格式'})


